import api from '../../utils/api'
const app = getApp()
const DEFAULT_PAGE = 0;

Page({
  //页面尺寸数据
  windowHeight: 0,
  screenHeight: 0,
  StartPageX: 0,
  CurrentView: DEFAULT_PAGE,
  /**
   * 页面的初始数据
   */
  data: {
    //等待框
    waitHidden: true,
    currentTab: 0, //预设当前项的值
    pics: [],
    isShow: true,
    imgUrl: [],
    title: "",
    description: "",
    price: "",
    categrory: "",
    requestParameters: "", //存放请求参数
    categoryList: [{
        id: 1,
        name: "手机数码",
        sellShow: true, // 在售页面显示
        buyShow: true // 求购页面不显示
      },
      {
        id: 2,
        name: "厨房厨具",
        sellShow: true,
        buyShow: true
      },
      {
        id: 3,
        name: "家用电器",
        sellShow: true,
        buyShow: true
      },
      {
        id: 4,
        name: "母婴",
        sellShow: true,
        buyShow: true
      },
      {
        id: 5,
        name: "图书",
        sellShow: true,
        buyShow: true
      },
      {
        id: 6,
        name: "工会",
        sellShow: true,
        buyShow: false
      },
      {
        id: 7,
        name: "其他",
        sellShow: true,
        buyShow: true
      }
    ],
    isDisabled: false,
    isLoading:false,
    toView: `card_${DEFAULT_PAGE}`,
    titlePlaceholderOptions: ['简要描述物品简介', '一句话说明你想买啥'],
    pricePlaceholderOptions: ['价格支持五位整数两位小数', '设定一个你能接收的价格'],
    detailPlaceholderOptions: ['详细介绍品牌型号，物品新旧，入手价格，来源等', '对于求购商品的要求，以及类似商品的参考'],
    titlePlaceholder: '',
    pricePlaceholder: '',
    detailPlaceholder: '',
    isIdle: '', // true-在售，false-求购
    lowPrice: '', //最低价
    highPrice: '' // 最高价
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (this.data.requestParameters == "") {
      this.setData({
        requestParameters: options,
        isIdle: options.isIdle,
        isDisabled:false,
        isLoading:false
      })
    }
    wx.hideShareMenu()
    //设置屏幕尺寸数据
    this.setData({
      windowHeight: app.globalData.windowHeight,
      screenHeight: app.globalData.screenHeight
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this
    if (that.data.requestParameters) {
      const options = that.data.requestParameters // 读取缓存的请求参数
      that.change(options.isIdle)
      if (options.isIdle == "true") {
        that.setData({
          titlePlaceholder: that.data.titlePlaceholderOptions[0],
          pricePlaceholder: that.data.pricePlaceholderOptions[0],
          detailPlaceholder: that.data.detailPlaceholderOptions[0]
        })
      } else if (options.isIdle == "false") {
        that.setData({
          titlePlaceholder: that.data.titlePlaceholderOptions[1],
          pricePlaceholder: that.data.pricePlaceholderOptions[1],
          detailPlaceholder: that.data.detailPlaceholderOptions[1]
        })
      }
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  /**上传图片 */
  uploadImage: function () {
    let that = this;
    let pics = that.data.pics;
    let imgUrl = that.data.imgUrl;
    wx.chooseImage({
      //限定上传张数x
      // count: 3 - pics.length,
      count: 1 - pics.length,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        let imgSrc = res.tempFilePaths;
        pics.push(imgSrc);
        //限定上传张数=1
        if (pics.length >= 1) {
          that.setData({
            isShow: false
          })
        }
        //显示等待框
        that.setData({
          pics: pics,
          waitHidden: false
        })
        wx.showLoading({
          title: '图片上传中',
        })
        //调取图片上传
        for (var i = 0; i < imgSrc.length; i++) {
          wx.uploadFile({
            //对象转字符串.join("")
            filePath: that.data.pics[i].join(""),
            name: 'img',
            url: api.upLoadPic,
            success: function (res) {
              if (res.statusCode == 200) {
                wx.hideLoading()
                var data = JSON.parse(res.data)
                if (data.data != null) {
                  that.data.imgUrl.push(data.data.imgUrl)
                }
                if (data.state == "1") {
                  wx.showToast({
                    title: '图片上传成功',
                  })
                } else if (data.state == "2") {
                  wx.showToast({
                    title: '图片上传失败',
                  })
                }
              } else {
                wx.showToast({
                  title: '图片上传失败，可能是因为图片过大',
                })
                that.setData({
                  pics: [],
                  isShow: true,
                  imgUrl: [],
                })
              }
            },
            fail: function (res) {
              wx.showToast({
                title: '图片上传失败',
              })
            },
            complete: () => {
              // console.log("complete")
            }
          })
        }
        // 设置图url
        that.setData({
          imgUrl: that.data.imgUrl,
          //隐藏等待框
          waitHidden: true
        })
      }
    })

  },

  /**删除图片 */
  deleteImg: function (e) {
    var that = this;
    var pics = this.data.pics;
    var imgUrl = this.data.imgUrl
    var index = e.currentTarget.dataset.index;
    pics.splice(index, 1);
    imgUrl.splice(index, 1);
    this.setData({
      pics: pics,
      imgUrl: imgUrl,
      isShow: true
    })
    // //图片url置空
    // that.setData({
    //   imgUrl: ""
    // })
  },
  shortInput: function (e) {
    this.setData({
      title: e.detail.value
    })
  },
  detailInput: function (e) {
    this.setData({
      description: e.detail.value
    })
  },
  priceInput: function (e) {
    this.setData({
      price: e.detail.value
    })
  },
  LowPriceInput: function (e) {
    this.setData({
      lowPrice: e.detail.value
    })
  },
  HighPriceInput: function (e) {
    this.setData({
      highPrice: e.detail.value
    })
  },
  tapToSubmit: function (e) {
    var that = this
    const options = that.data.requestParameters // 读取缓存的请求参数
    if (that.data.currentTab == "") {
      wx.showToast({
        title: '请选择类型',
      })
      return
    } else if (that.data.title == "") {
      wx.showToast({
        title: '请输入标题',
      })
      return
    } else if (that.data.description == "") {
      wx.showToast({
        title: '请输入详情',
      })
      return
    } else if (that.data.imgUrl.length == 0) {
      if (options.isIdle == "true") {
        wx.showToast({
          title: '请上传图片',
        })
        return
      }
    } else {
      // console.log("imgurl here", that.data.imgUrl)
    }
    if (options.isIdle == "true") {
      if (that.data.price == "") {
        wx.showToast({
          title: '请输入价格',
        })
        return
      }
    }

    if (options.isIdle == "false") {
      if (that.data.lowPrice == "" ) {
        wx.showToast({
          title: '请输入最低价',
        })
        return
      } else if (that.data.highPrice == "") {
        wx.showToast({
          title: '请输入最高价',
        })
        return
      } else if (parseFloat(that.data.lowPrice) >= parseFloat(that.data.highPrice)) {
        wx.showToast({
          title: '最高价需高于最低价',
          icon: 'none'
        })
        return
      }
    }
    if (options) {
      that.setData({
        isDisabled:true,
        isLoading:true
      })
      if (options.isIdle == "true") { // 发布闲置
        wx.request({
          url: api.goodsAdd,
          method: "POST",
          data: {
            title: that.data.title,
            description: that.data.description,
            price: parseFloat(that.data.price),
            // imgUrl: JSON.parse(that.data.imgUrl),
            imgUrl: that.data.imgUrl[0],
            category: that.data.currentTab
          },
          header: {
            'content-Type': 'application/json;charset=UTF-8',
            'token': wx.getStorageSync('token')
          },
          success(e) {
            if (e.data.state == 1) {

              wx.showToast({
                title: '发布成功',
              })
              setTimeout(res => {
                wx.navigateBack({
                  delta: 1,
                })
              }, 2000)
            } else {
              wx.showToast({
                title: '发布失败',
              })
            }
          },
        })
      } else if (options.isIdle == "false") { // 发布求购
        wx.request({
          url: api.addPurchaseInfo,
          method: "POST",
          data: {
            buyerId: wx.getStorageSync('logindata').data.id,
            title: that.data.title,
            description: that.data.description,
            bottomPrice: parseFloat(that.data.lowPrice),
            peakPrice: parseFloat(that.data.highPrice),
            // imgUrl: JSON.parse(that.data.imgUrl),
            imgUrl: that.data.imgUrl[0],
            category: that.data.currentTab
          },
          header: {
            'content-Type': 'application/json;charset=UTF-8',
            'token': wx.getStorageSync('token')
          },
          success(e) {
            if (e.data.state == 1) {

              wx.showToast({
                title: '发布成功',
              })
              setTimeout(res => {
                wx.navigateBack({
                  delta: 1,
                })
              }, 2000)

            } else {
              wx.showToast({
                title: '发布失败',
              })
            }
          },
          fail(e) {
            // console.log(e)
          }
        })
      }
      setTimeout(function() {
        that.setData({
          isDisabled:false,
          isLoading:false
        })
      },2000)
    }
  },
  touchStart(e) {
    this.StartPageX = e.changedTouches[0].pageX;
  },

  touchEnd(e) {
    const moveX = e.changedTouches[0].pageX - this.StartPageX;
    const maxPage = this.data.categoryList.length - 1;
    if (Math.abs(moveX) >= 50) {
      if (moveX > 0) {
        this.CurrentView = this.CurrentView !== 0 ? this.CurrentView - 1 : 0;
      } else {
        this.CurrentView = this.CurrentView !== maxPage ? this.CurrentView + 1 : maxPage;
      }
    }
    this.setData({
      toView: `card_${this.CurrentView}`
    });
  },
  swichNav: function (e) {
    var cur = e.target.dataset.current; //查询标题序号
    if (this.data.currentTab == cur) {
      return false;
    } else {
      this.setData({
        currentTab: cur
      })
    }
  },

  // 更改页面头
  change: function (isIdle) {
    if (isIdle == "true") {
      wx.setNavigationBarTitle({
        title: '发布闲置'
      })
    } else if (isIdle == "false") {
      wx.setNavigationBarTitle({
        title: '发布求购'
      })
    }
  }
})